//
//  BiSaleExecuteListViewController.m
//  TrunkIndustryManageSystem
//
//  Created by WT_lyy on 15/4/21.
//  Copyright (c) 2015年 李璐西. All rights reserved.
//

#import "BiSaleListViewController.h"
#import "BiSaleApplyViewController.h"
#import "BiSaleExecuteCheckViewController.h"
#import "BiSaleApplyManageViewController.h"
#import "BiContrCheckViewController.h"
#import "BiAssociateCheckViewController.h"
#import "SaleListCell.h"
#import "BiCarSaleCheckEntity.h"
#import "BiCarSaleContractEntity.h"

#import "BiIndexSaleViewController.h"
#import "MJRefresh.h"
@interface BiSaleListViewController ()<UITableViewDataSource,UITableViewDelegate>{

    UITableView * _tableView;
    
    NSMutableArray * _saleExecuteList;
    
    BOOL isHaveSale;
}

@end

@implementation BiSaleListViewController

- (id)init
{
    self = [super init];
    if (self)
    {
        _saleExecuteList = [[NSMutableArray alloc] init];
        
    }
    return self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setNavBackBtn];
    
    
    if (1 == self.type) {
        
        [self setNavBarTitle:@"行销申请列表"];
    }else if (2 == self.type){
        
        [self setNavBarTitle:@"行销审批列表"];
    }else if (3 == self.type){
        
        [self setNavBarTitle:@"行销执行列表"];
    }else if (4 == self.type){
        
        [self setNavBarTitle:@"整车销售合同上传列表"];
    }else if (5 == self.type){
        
        [self setNavBarTitle:@"车辆交接列表"];
    }
    
    
    [self setNavBarWithHidden:NO];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, [self viewTop], MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT-[self viewTop])];
    
    if (1 == self.type) {
        _tableView.frame = CGRectMake(0, [self viewTop], MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT-[self viewTop]-40);
        
        UIButton * btnApplysale = GET_BUTTON(CGRectMake(0, MAIN_SCREEN_HEIGHT-40, MAIN_SCREEN_WIDTH, 40), 15, NO, [UIColor whiteColor]);
        
        btnApplysale.backgroundColor = UIColorFromRGB(BLUE_COLOR_VALUE);
        
        [btnApplysale setTitle:@"申请行销" forState:UIControlStateNormal];
        
        [self.view addSubview:btnApplysale];
        
        [btnApplysale addTarget:self action:@selector(btnApplySaleClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    _tableView.delegate = self;
    
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    
    _tableView.rowHeight = 80;
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self setupRefresh];
    
}

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    if (1 == self.type || 2 == self.type || 3 == self.type){
        NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:[BiUserEntity sharedInstance].userid,@"userId",
                                  @"1",@"page",
                                  PAGESIZE,@"pageSize",
                                  [NSString stringWithFormat:@"%i",(int)self.type-1],@"status",
                                  nil];
        
        [[BiNetEngine shareInstance] requestCarSaleCheckList:self paraDict:paraDic];
        
        [self asyshowHUDView:WAITING CurrentView:self];
        
    }else if (4 == self.type || 5 == self.type){
        
        NSString * status = nil;
        
        if (4 == self.type) {
            
            status = @"3";
        }else if (5 == self.type){
            
            status = @"7";
        }
        
        NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:[BiUserEntity sharedInstance].userid,@"userId",
                                  @"1",@"page",
                                 PAGESIZE,@"pageSize",
                                  status,@"orderStatus",
                                  nil];
        
        [[BiNetEngine shareInstance] requestCarSaleContracAssoList:self paraDict:paraDic];
        
        [self asyshowHUDView:WAITING CurrentView:self];
        
    }
    
}


/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
//#warning 自动刷新(一进入程序就下拉刷新)
//    [_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _tableView.headerPullToRefreshText = @"下拉刷新";
    _tableView.headerReleaseToRefreshText = @"松开即可刷新";
    _tableView.headerRefreshingText = @"刷新中~";
    
    _tableView.footerPullToRefreshText = @"上拉加载更多数据";
    _tableView.footerReleaseToRefreshText = @"松开马上加载";
    _tableView.footerRefreshingText = @"加载中~";
}


#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    NSLog(@"headerRereshing");
    
    if (1 == self.type || 2 == self.type || 3 == self.type){
        NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:[BiUserEntity sharedInstance].userid,@"userId",
                                  @"1",@"page",
                                  PAGESIZE,@"pageSize",
                                  [NSString stringWithFormat:@"%i",(int)self.type-1],@"status",
                                  nil];
        
        [[BiNetEngine shareInstance] requestCarSaleCheckList:self paraDict:paraDic];
        
        [self asyshowHUDView:WAITING CurrentView:self];
        
    }else if (4 == self.type || 5 == self.type){
        
        NSString * status = nil;
        
        if (4 == self.type) {
            
            status = @"3";
        }else if (5 == self.type){
            
            status = @"7";
        }
        
        NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:[BiUserEntity sharedInstance].userid,@"userId",
                                  @"1",@"page",
                                  PAGESIZE,@"pageSize",
                                  status,@"orderStatus",
                                  nil];
        
        [[BiNetEngine shareInstance] requestCarSaleContracAssoList:self paraDict:paraDic];
        
       // [self asyshowHUDView:WAITING CurrentView:self];
        
    }
    

}

- (void)fffff{

    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];

}

- (void)footerRereshing
{

    [self performSelector:@selector(fffff) withObject:nil afterDelay:2];
    NSLog(@"footerRereshing");
}


- (void)btnApplySaleClick{

    BiSaleApplyViewController * apltVc = [[BiSaleApplyViewController alloc] init];
    
    
    [self.navigationController pushViewController:apltVc animated:YES];
}

-(void)onNavBackBtnClick{

    for (UIViewController * Vctrl in self.navigationController.viewControllers) {
        if ([Vctrl isKindOfClass:[BiIndexSaleViewController class]]) {
            
            [self.navigationController popToViewController:Vctrl animated:YES];
            
            break;
        }
    }
}

#pragma -mark UitabeViewDelegate 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    BiCarSaleCheckEntity * centity = _saleExecuteList[indexPath.row];
    
    switch (self.type) {
        case 1:{
        
            BOOL isExist = NO;
            
            BiSaleApplyViewController * aptVc = nil;
            
            for (UIViewController * Vctrl in self.navigationController.viewControllers) {
                
                if ([Vctrl isKindOfClass:[BiSaleApplyViewController class]]) {
                    
                    isExist = YES;
                    
                    aptVc = (BiSaleApplyViewController *)Vctrl;
                    
                    break;
                }
            }
            
            if (isExist) {
                
                aptVc.Centity = centity;
                
                [self.navigationController popViewControllerAnimated:YES];
                
            }else{
                
                BiSaleApplyViewController * apltVc = [[BiSaleApplyViewController alloc] init];
                
                apltVc.Centity = centity;
                
                [self.navigationController pushViewController:apltVc animated:YES];
            }
            
        }
            break;
        case 2:{
        
            BiSaleApplyManageViewController * chkAgrVc = [[BiSaleApplyManageViewController alloc] init];
            
            chkAgrVc.Centity = centity;
            
            [self.navigationController pushViewController:chkAgrVc animated:YES];
        }
            
            break;
        case 3:{
            BiSaleExecuteCheckViewController * exeVc = [[BiSaleExecuteCheckViewController alloc] init];
            
            exeVc.Centity = centity;
            
            if (!isHaveSale) {
                
                [self.navigationController pushViewController:exeVc animated:YES];
                
                break;
            }
            
            if ([centity.isExecuted intValue]==1) {
                
                [self.navigationController pushViewController:exeVc animated:YES];
                
                break;
            }
            
            [self showMessage:@"有行销正在执行！"];
            
        }
            break;
        case 4:{
            
            BiCarSaleContractEntity * conentity = _saleExecuteList[indexPath.row];
            
            BiContrCheckViewController * contractVc = [[BiContrCheckViewController alloc] init];
            
            contractVc.Centity = conentity;
            
            [self.navigationController pushViewController:contractVc animated:YES];
        }
            break;
        case 5:{
            
            BiCarSaleContractEntity * conentity = _saleExecuteList[indexPath.row];
            
            BiAssociateCheckViewController * contractVc = [[BiAssociateCheckViewController alloc] init];
            
            contractVc.Centity = conentity;
            
            [self.navigationController pushViewController:contractVc animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma -mark UitabeViewDatasource

- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (_saleExecuteList) {
        
        return _saleExecuteList.count;
    }
    
    return 0;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SaleListCell * cell = (SaleListCell *)[self cellForXingXiaoRowAtIndexPath:indexPath];
    
    return cell;
}

- (SaleListCell *)cellForXingXiaoRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString * myIndentifier = @"SaleListCell";
    
    SaleListCell * cell = (SaleListCell *)[_tableView dequeueReusableCellWithIdentifier:myIndentifier];
    
    if (!cell)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"SaleListCell" owner:self options:nil] firstObject];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    [cell setTiltleType:self.type];
    
    if (1 == self.type || 2 == self.type || 3 == self.type) {
        BiCarSaleCheckEntity * entity = [_saleExecuteList objectAtIndex:indexPath.row];
        
        cell.labApplyer.text = entity.userApplyName;
        
        cell.labDes.text = entity.destination;
        
        cell.labTime.text = entity.gooffTime;
        
        if (3 == self.type) { //正在执行的行销以做区别

            if ([entity.isExecuted intValue] == 1) {
                //正在执行的行销
                isHaveSale = YES;
                
                cell.backgroundColor = [UIColor orangeColor];
            }else if ([entity.isExecuted intValue] == 2){
            
                //结束行销未审核
                cell.backgroundColor = [UIColor yellowColor];
            }
        }
    }else if (4 == self.type ){
    
        BiCarSaleContractEntity * entity = [_saleExecuteList objectAtIndex:indexPath.row];
        
        cell.labApplyer.text = entity.member_name;
        
        cell.labTime.text = entity.carOrder_orderTime;
        
        cell.labDes.text = entity.carOrder_connectCarTime;
        
    }else if (5 == self.type){
        
        BiCarSaleContractEntity * entity = [_saleExecuteList objectAtIndex:indexPath.row];
        
        cell.labApplyer.text = entity.member_name;
        
        cell.labTime.text = entity.member_address;
        
        cell.labDes.text = entity.member_phone;
        
    }

    return cell;

}

#pragma -mark Net Delegate
- (void)onNetEngineResponse:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    
    [self removeHUDView:self];
    
    NSDictionary * entity_ = (NSDictionary *)entity;
    

    if ([entity_[@"response_status"] integerValue] != 200) {
        
        
      //  [self showMessage:entity_[@"result_info"]];
        
        
        return;
        
    }

    
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    
    [_saleExecuteList removeAllObjects];
    
    [_saleExecuteList addObjectsFromArray:entity_[@"data"]];
    
    if (_saleExecuteList.count == 0) {
        
        [self showMessage:@"没有更多数据了"];
        
    }
    isHaveSale = NO;
    [_tableView reloadData];
    
}
- (void)onNetEngineResponseFail:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    [self removeHUDView:self];
}

@end
